from flask import Blueprint, render_template, jsonify, request
from python.extensions import db
from python.model.weather import WeatherData
from sqlalchemy import func, extract
import datetime

# 创建风力等级季节分布分析蓝图，URL前缀为/menu
wind_visualization_bp = Blueprint('wind_visualization', __name__, url_prefix='/menu')


@wind_visualization_bp.route('/wind_grade', methods=['GET'])
def wind_grade():
    """渲染风力等级季节分布页面"""
    # 获取所有城市
    cities = db.session.query(WeatherData.city).distinct().all()
    cities = [city[0] for city in cities]

    # 获取所有年份
    years = db.session.query(extract('year', WeatherData.date)).distinct().all()
    years = [str(int(year[0])) for year in years]  # 转换为整数再转为字符串
    years.sort(reverse=True)  # 按年份降序排列

    # 默认选择第一个城市和最近的年份
    initial_city = cities[0] if cities else ""
    initial_year = years[0] if years else ""

    return render_template(
        'menu/wind_visualization.html',  # 模板路径
        cities=cities,
        years=years,
        initial_city=initial_city,
        initial_year=initial_year
    )


@wind_visualization_bp.route('/seasonal_wind_grades', methods=['GET'])
def seasonal_wind_grades():
    """提供季节风力等级分布数据"""
    city = request.args.get('city', '')
    year = request.args.get('year', '')

    if not city:
        return jsonify({"error": "城市参数不能为空"}), 400

    try:
        # 定义季节映射
        seasons = ['春季', '夏季', '秋季', '冬季']
        season_months = {
            '春季': [3, 4, 5],
            '夏季': [6, 7, 8],
            '秋季': [9, 10, 11],
            '冬季': [12, 1, 2]
        }

        # 构建基础查询
        query = db.session.query(WeatherData)

        # 应用城市和年份过滤
        query = query.filter(WeatherData.city == city)
        if year:
            query = query.filter(extract('year', WeatherData.date) == int(year))

        # 过滤掉风力等级为空的数据
        query = query.filter(WeatherData.wind_level != None)

        # 执行查询获取所有符合条件的记录
        results = query.all()

        if not results:
            return jsonify({
                "seasons": seasons,
                "wind_grades": [],
                "grade_data": [],
                "error": "未找到该城市的风力数据"
            })

        # 找出所有不同的风力等级
        wind_grades = sorted(list(set([result.wind_level for result in results])))

        # 初始化数据结构：每个风力等级在每个季节的天数
        grade_data = {grade: {season: 0 for season in seasons} for grade in wind_grades}

        # 统计每个风力等级在每个季节的天数
        for result in results:
            month = result.date.month
            wind_grade = result.wind_level

            # 确定月份所属的季节
            for season, months in season_months.items():
                if month in months:
                    grade_data[wind_grade][season] += 1
                    break

        # 格式化数据为前端所需的结构
        formatted_data = []
        for grade in wind_grades:
            grade_entry = {
                "风力等级": grade,
                "春季": grade_data[grade]["春季"],
                "夏季": grade_data[grade]["夏季"],
                "秋季": grade_data[grade]["秋季"],
                "冬季": grade_data[grade]["冬季"]
            }
            formatted_data.append(grade_entry)

        return jsonify({
            "city": city,
            "year": year,
            "seasons": seasons,
            "wind_grades": wind_grades,
            "data": formatted_data
        })

    except Exception as e:
        print(f"获取季节风力等级数据时出错: {e}")
        return jsonify({"error": "获取数据时出错，请稍后重试"}), 500